package com.yudaob2b.elong.task;

import com.yudaob2b.common.utils.ListUtil;
import com.yudaob2b.elong.entity.vo.HotelDataRpResult;
import com.yudaob2b.elong.entity.vo.HotelRatePlan;
import com.yudaob2b.elong.enums.EnumPaymentType;
import com.yudaob2b.elong.service.HotelRpService;
import com.yudaob2b.elong.service.HttpStaticService;
import org.frameworkset.elasticsearch.client.ClientInterface;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.io.Serializable;
import java.util.List;

/**
 * @author Kidd.Tan
 * @email 298023780@qq.com
 * @date 7/20/18 8:42 PM
 */
public class DataRpLocalTask implements Runnable, Serializable {
    private static Logger dataRpLocalTaskLogger = LoggerFactory.getLogger("dataRpLocalTaskLogger");

    /**
     * 酒店id，最多10个
     */
    private List<String> hotelIds;
    private HttpStaticService httpStaticService;
    private HotelRpService hotelRpService;
    private ThreadPoolTaskExecutor dataRpDbTaskExecutor;
    private ClientInterface clientUtil;
    // 线程添加/更新列表数
    private final int TASK_LIST_COUNT = 500;

    public DataRpLocalTask(List<String> hotelIds, HttpStaticService httpStaticService
            , HotelRpService hotelRpService, ThreadPoolTaskExecutor dataRpDbTaskExecutor
            , ClientInterface clientUtil) {
        this.hotelIds = hotelIds;
        this.httpStaticService = httpStaticService;
        this.hotelRpService = hotelRpService;
        this.dataRpDbTaskExecutor = dataRpDbTaskExecutor;
        this.clientUtil = clientUtil;
    }

    @Override
    public void run() {
        long start = System.currentTimeMillis();
        if (hotelIds.size() <= 10) {
            StringBuilder hotelIdBuilder = new StringBuilder();
            for (String hotelId : hotelIds) {
                hotelIdBuilder.append(hotelId).append(",");
            }

            // 10个酒店id查询一次
            HotelDataRpResult rpResult = httpStaticService.gethotelDataRp(hotelIdBuilder.toString(), EnumPaymentType.Prepay, null);
            // 重置查询的酒店id
            if (rpResult != null && "0".equals(rpResult.getCode()) && rpResult.getResult().getHotels().size() > 0) {
                List<List<HotelRatePlan>> listPage = ListUtil.split(rpResult.getResult().getHotels(), TASK_LIST_COUNT);
                for (List<HotelRatePlan> rpList : listPage) {
                    DataRpLocalDbTask dbTask = new DataRpLocalDbTask(rpList, hotelRpService,  clientUtil);
                    dataRpDbTaskExecutor.execute(dbTask);
                }
            }
        }
        //dataRateLocalTaskLogger.info("---价格落地线程总耗时：---{}", System.currentTimeMillis() - start);
    }
}
